package com.leoren.run.activity.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.leoren.run.R;
import com.leoren.run.activity.run.CreateMapActivity;
import com.leoren.run.activity.run.RunMapRouteAdapter;
import com.leoren.run.activity.run.RunRecordActivity;
import com.leoren.run.common.ResponseCode;
import com.leoren.run.common.ServerResponse;
import com.leoren.run.common.UrlConstants;
import com.leoren.run.log.L;
import com.leoren.run.utils.GsonUtil;
import com.leoren.run.utils.Http.OkHttp.CommonOkHttpClient;
import com.leoren.run.utils.Http.OkHttp.exception.OkHttpException;
import com.leoren.run.utils.Http.OkHttp.listener.DisposeDataHandle;
import com.leoren.run.utils.Http.OkHttp.listener.DisposeDataListener;
import com.leoren.run.utils.Http.OkHttp.request.CommonRequest;
import com.leoren.run.utils.ToastUtil;
import com.leoren.run.vo.AreaDivision;
import com.leoren.run.vo.MapRouteVo;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 跑步Fragment
 */
public class RunFragment extends Fragment implements AMapLocationListener{

    private View rootView;

    private Toolbar toolbar;

    private RecyclerView routeListView;
    private List<MapRouteVo> mapRouteVoList;
    private LinearLayoutManager manager;
    private RunMapRouteAdapter adapter;

    private AMapLocationClient client = null;
    private AMapLocationListener listener;
    private AMapLocationClientOption option;


    private AreaDivision division = null;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_run, container, false);

        initLocation();

        initViews();

        return rootView;
    }

    /**
     * 初始化定位所需控件
     */
    private void initLocation(){
        client = new AMapLocationClient(this.getActivity().getApplicationContext());
        client.setLocationListener(this);

        option = new AMapLocationClientOption();
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Sport);
        if(null != client){
            client.setLocationOption(option);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            client.stopLocation();
            client.startLocation();
        }
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setInterval(1000);
        option.setNeedAddress(true);
        option.setWifiScan(true);
        option.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);
        client.setLocationOption(option);
        client.startLocation();
    }

    /**
     * 定位信息回调
     * @param aMapLocation
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if(aMapLocation.getErrorCode() == 0){
            L.e(aMapLocation.getLatitude() + "");
            L.e(aMapLocation.getLongitude() + "");
            L.e("address=" + aMapLocation.getAddress());
            String province = aMapLocation.getProvince();
            String city = aMapLocation.getCity();
            String district = aMapLocation.getDistrict();
            L.e(province);
            L.e(city);
            L.e(district);
            division = new AreaDivision(province, city, district);
            initDate();
            client.stopLocation();
            if(division.getCity() != null || division.getCity().equals("")){
                client.stopLocation();
            }else {
                division = new AreaDivision("山西省", "太原市", "尖草坪区");
                client.stopLocation();
            }
            L.e(GsonUtil.GenerateJsonStr(division));
        }else {
            L.e("定位失败===================");
        }
    }

    /**
     * 根据定位信息查询当地地图
     */
    private void initDate(){
        RequestBody body = new FormBody.Builder()
                .add("province", division.getProvince())
                .add("city", division.getCity())
                .add("district", division.getDistrict())
                .build();
        final Request request = CommonRequest.createPostRequest(UrlConstants.MAP_GET_ALL_MAP, body);
        L.e("url = " + request.url());
        CommonOkHttpClient.post(request, new DisposeDataHandle(new DisposeDataListener() {
            @Override
            public void onSuccess(String responseStr) {
                ServerResponse<List<MapRouteVo>> response = GsonUtil.formatJsonToResponseMapRouteList(responseStr);
                L.e("response = " + response.toString());
                if(response == null){
                    onFailure(new OkHttpException(ResponseCode.NETWORK_ERROR.getCode(), ResponseCode.NETWORK_ERROR.getValue()));
                    return;
                }
                if(!response.isSuccess()){
                    onFailure(new OkHttpException(ResponseCode.UNKNOWN_ERROR.getCode(), response.getMsg()));
                    return;
                }
                if (response.getStatus() == ResponseCode.SUCCESS.getCode()) {
                    mapRouteVoList = response.getData();
                    if(mapRouteVoList == null){
                        mapRouteVoList = new ArrayList<>();
                    }
                    L.e(mapRouteVoList.toString() + "Log=======================================");
                    initRouteList(mapRouteVoList);
                }
                ToastUtil.MakeToast(response.getMsg());
            }

            @Override
            public void onFailure(OkHttpException e) {
                ToastUtil.MakeToast(e.getMsg() + "");
            }
        }));

    }

    /**
     * 显示地图信息  展示地图列表
     * @param mapRouteVos
     */
    private void initRouteList(List<MapRouteVo> mapRouteVos){
        adapter = new RunMapRouteAdapter(this.getActivity(), mapRouteVos);
        manager = new LinearLayoutManager(this.getActivity());
        routeListView.setAdapter(adapter);
        routeListView.setLayoutManager(manager);
        adapter.notifyDataSetChanged();
    }

    /**
     * 初始化列表
     */
    private void initViews(){
        toolbar = rootView.findViewById(R.id.run_toolbar);
        ((AppCompatActivity) Objects.requireNonNull(getActivity())).setSupportActionBar(toolbar);
        setHasOptionsMenu(true);
        routeListView = rootView.findViewById(R.id.run_route_list_view);
    }


    /**
     * 展开该页面菜单栏所需
     * @param menu
     * @param inflater
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.run_menu, menu);
        if(menu != null){
            if(menu.getClass() == MenuBuilder.class){
                try {
                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                }catch (Exception e){

                }
            }
        }
    }

    /**
     * 选择菜单栏点击事件
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.publish_map:
                startCreateMap();
                break;
            default:
                break;
        }
        return true;
    }


    /**
     * 跳转到手机制图页面
     */
    private void startCreateMap(){
        Intent intent = new Intent(getContext(), CreateMapActivity.class);
        startActivity(intent);
    }


    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();

    }


}
